// 作者 黄豪琦
// 时间: 2020-03-27 09:14
// 说明: 

var websocket = null;

function initWebSocket() {
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8848/articleRealSave");
    } else {
        h_alert("你的浏览器不支持WebSocket,将无法实时保存文章修改");
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {

    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {

    };

    //接收到消息的回调方法
    websocket.onmessage = function (event) {

    };

    //连接关闭的回调方法
    websocket.onclose = function () {

    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    };
}

function saveArticle(msg) {
    websocket.send(msg);
}

$(function () {

    initWebSocket();

    // compile("article-content");

    const editor = editormd("editormd", {
        path: '/plugins/editor/lib/',
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "/editor/upload/img",
        //这个配置在simple.html中并没有，但是为了能够提交表单，
        // 使用这个配置可以让构造出来的HTML代码直接在第二个隐藏的textarea域中，方便post提交表单。
        saveHTMLToTextarea: true
    });

    //监听编辑区 实时保存文章
    $(document).on("input propertychange", ".CodeMirror-wrap", function () {
        const title = $("#title").val();
        const content = $("#content").val();
        const htmlContent = $("#htmlContent").val();
        const msg = "{\"title\":\"" + title + "\"," +
            "\"content\":\"" + JSON.stringify(content).replace(/\"/g,"'") + "\"," +
            "\"htmlContent\":\"" + JSON.stringify(htmlContent).replace(/\"/g,"'") + "\"}";
        saveArticle(msg);
    });

    $("#commit-btn").click(function () {
        const title = $("#title").val();
        const content = $("#content").val();
        const htmlContent = $("#htmlContent").val();
        $.ajax({
            url: "/editor/submit",
            type: "post",
            data: {articleTitle: title, articleContent: content, articleHtmlContent: htmlContent, articleStatus: 1},
            success: function (data) {
                if (data.code === 1) {
                    h_alert(data.message);
                    h_route("/article/detail/"+data.articleCode);
                } else {
                    h_alert(data.message);
                }
            },
            error: function (e) {
                h_alert('上传失败');
            }
        })
    });
});